package com.lanou3g.musicenjoy.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.adapter.NewSongListAdapter;
import com.lanou3g.musicenjoy.custom.MyListView;
import com.lanou3g.musicenjoy.entity.NewSongList;
import com.lanou3g.musicenjoy.entity.NewSongListEntity;
import com.lanou3g.musicenjoy.entity.PlayMusicEntity;
import com.lanou3g.musicenjoy.eventbus.MyEvent;
import com.lanou3g.musicenjoy.volley.VolleySingleton;
import com.squareup.picasso.Picasso;


import java.util.ArrayList;
import java.util.List;


import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * Created by 李宁 on 15/10/27.
 * 新歌榜页面
 */
public class NewSongListFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private VolleySingleton volleySingleton;
    private NewSongListAdapter adapter;
    private StringRequest stringRequest;
    private String startUrl;
    private List<NewSongList.SongListEntity> newSongList;
    private List<PlayMusicEntity> data = new ArrayList<>();
    private ProgressDialog dialog;//加载中
    private int clickPosition;//记录当前点击的位置
    private int numOfData;//data的总长度
    private int numOfNow;//已经完成的长度
    private ImageView newSongList_head;
    private ImageView back;
    private Toolbar coordinator_toolbar;
    private CollapsingToolbarLayout collapsing_toolbar;
    private MyListView newSongList_listView;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_newsonglist, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        newSongList_head = (ImageView) getActivity().findViewById(R.id.newSongList_head);
        back = (ImageView) getActivity().findViewById(R.id.back);
        coordinator_toolbar = (Toolbar) getActivity().findViewById(R.id.coordinator);
        collapsing_toolbar = (CollapsingToolbarLayout) getActivity().findViewById(R.id.collapsing);
        newSongList_listView = (MyListView) getActivity().findViewById(R.id.newSongList_listView);
        newSongList_listView.setOnItemClickListener(this);
        back.setOnClickListener(this);

        coordinator_toolbar.setTitle("乐享音乐");
        collapsing_toolbar.setCollapsedTitleTextColor(0xffffffff);
        collapsing_toolbar.setExpandedTitleColor(0x00ffffff);
        //接收传值
        Bundle bundle = getArguments();
        String url = bundle.getString("url");
        int type = bundle.getInt("type", 10);
        Picasso.with(getActivity()).load(url).into(newSongList_head);
        startUrl = "http://tingapi.ting.baidu.com/v1/restserver/ting" +
                "?from=android&version=5.6.5.0&method=baidu.ting.billboard.billList&format" +
                "=json&type=" + type + "&offset=0&size=100&fields=song_id%2Ctitle%2Cauthor%2Calbum_title%2Cpic" +
                "_big%2Cpic_small%2Chavehigh%2Call_rate%2Ccharge%2Chas_mv_mobile%2Clearn%2Csong_source%2Ckorean_bb_song;";

        Log.i("xinxinixn", startUrl + "");
        volleySingleton = VolleySingleton.getInstance(getActivity());
        adapter = new NewSongListAdapter(getActivity());
        this.getUrl();

    }

    public void getUrl() {
        stringRequest = new StringRequest(startUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                NewSongList result = gson.fromJson(response, NewSongList.class);
                if (result != null) {
                    newSongList = result.getSong_list();
                }
                //加载Adapter
                adapter.setData(newSongList);
                newSongList_listView.setAdapter(adapter);
                //加载完成后隐藏
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        volleySingleton.addQueue(stringRequest);
        //加载中
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage("请稍等,乐享音乐加载中...");
        dialog.show();
    }

    //网络解析
    private void getInternetData(String url, final int position) {

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {//成功回调
                //进行解析
                NewSongListEntity entity = JSON.parseObject(s, NewSongListEntity.class);
                if (entity != null) {//解析成功,这是其中一个音乐的播放地址

                    String url = entity.getSongurl().getUrl().get(0).getShow_link();//获得了URL

                    String pic = newSongList.get(position).getPic_big();
                    String singerName = newSongList.get(position).getAuthor();
                    String songName = newSongList.get(position).getTitle();

                    //设置data的相应位置的数据
                    data.get(position).setUrl(url);
                    data.get(position).setPicUrl(pic);
                    data.get(position).setSingerName(singerName);
                    data.get(position).setSongName(songName);
                    Log.i("NewSongListFragment", "getURl->position" + position);

                    numOfNow++;
                    Log.i("NewSongListFragment", "当前已完成" + numOfNow);

                    if (numOfNow >= numOfData) {
                        //所有数据均已加载完成
                        EventBus.getDefault().post(new MyEvent.PassData(data, clickPosition));
                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                numOfNow++;
                Log.i("NewSongListFragment", "当前已完成" + numOfNow);

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {
        //结束,回到上一个fragment
        getFragmentManager().popBackStack();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        getAllUrl(position);

    }

    private void getAllUrl(int position) {
        clickPosition = position;//记录下当前点击的position
        numOfData = newSongList.size();//设置总长度
        numOfNow = 0;//设置当前完成的长度
        for (int i = 0; i < newSongList.size(); i++) {//获得所有的Url进行网络数据的拉取
            String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                    newSongList.get(i).getSong_id() + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                    "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
            getInternetData(url, i);//i记录了当前正在解析哪个URL

            //让data集合拥有跟数据匹配的长度
            PlayMusicEntity playMusicEntity = new PlayMusicEntity();
            data.add(playMusicEntity);
        }
    }
}
